/*
 * Project: jcerticles
 * Copyright(c) 2011 jcerticles
 * All rights reserved.
 *
 * $Revision $, last modified $Date $ by $Author $
 */
package com.quintilis31.home.persistence.type.impl.sql.jpa.jpaimpl;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import sun.reflect.generics.reflectiveObjects.TypeVariableImpl;

import com.quintilis31.home.persistence.type.impl.sql.jpa.IGenericBaseDAO;

/**
 * The base Generic DAO interface
 *
 * TODO... Write Javadoc...
 *
 * @author    Jothi Shankar Kumar. S
 * @since     1.6
 *
 * @param <T> the entity type
 * @param <ID> the primary key type
 *
 */
public abstract class GenericJPADAO < T, ID extends Serializable > implements IGenericBaseDAO < T, ID > {

    protected Class<T> entityClass;

    @PersistenceContext
    protected EntityManager entityManager;

    @SuppressWarnings("unchecked")
	public GenericJPADAO() {    	
    	if(!(((ParameterizedType) getClass()
                .getGenericSuperclass()).getActualTypeArguments()[0] instanceof TypeVariableImpl)) {        	
        	this.entityClass = (Class<T>) ((ParameterizedType) getClass()
                    .getGenericSuperclass()).getActualTypeArguments()[0];    		    		
    	}    	
    }

   /**
    * {@inheritDoc}
    */
    public void save(T entity) {
        entityManager.persist(entity);
    }

   /**
    * {@inheritDoc}
    */
    public void delete(T entity) {
        entityManager.remove(entity);
    }

   /**
    * {@inheritDoc}
    */
    public T findById(Long id) {
        return entityManager.find(entityClass, id);
    }
}